import threading
import tushare as ts
from sqlalchemy import create_engine
import logging
import pandas as pd
from DatetimeUtils import choose_day
from PledgeDetailData import deal_append as deal_append_pledgedetail
import constant

"""
根据ts_code更新，无其他条件
"""
# 日志
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
# 初始化数据库连接:
engine = create_engine(
    constant.get_db_path(),
    max_overflow=0,  # 超过连接池大小外最多创建的连接数
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 连接池中没有线程最多等待时间，否则报错
    pool_recycle=-1,  # 多久之后对连接池中的连接进行回收（重置）-1不回收
)

pro = ts.pro_api(constant.get_pro_token())

'''
更新各类数据定时器
'''


def fun_timer():

    sql = 'select s.ts_code from stock s'
    stock_list = pd.read_sql(sql, engine)
    if len(stock_list) > 0:
        for i in range(0, len(stock_list)):
            ts_code = stock_list.loc[i].ts_code
            deal_append_pledgedetail(ts_code, engine, pro)

    global timer
    timer = threading.Timer(86400, fun_timer)
    timer.start()


def update_test(ts_code):
    """
    单项更新，适合测试
    """
    deal_append_pledgedetail(ts_code, engine, pro)


test_flag = False
if test_flag:
    update_test('688628.SH')
else:
    fun_timer()
    # timer = threading.Timer(1, fun_timer)
    # timer.start()